package com.lcc.bank.tools.handle;

import cn.hutool.core.util.StrUtil;
import com.fingard.gardpay.common.constant.MsgFieldConstant;
import com.lcc.bank.tools.pojo.ReconciliationNoticeResp;
import com.lcc.bank.tools.pojo.ReturnConfigDTO;
import com.lcc.bank.tools.pojo.ReturnInfoDTO;
import com.lcc.bank.tools.util.StringUtil;
import com.lcc.bank.tools.util.XmlUtil;
import com.lcc.bank.tools.template.TemplateHolder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;

import java.util.Arrays;
import java.util.List;

/**
 * @author lincc
 * @version 1.0  2019/2/22
 */
@Slf4j
public class MsgHandleThread implements Runnable {
    private ChannelHandlerContext temp;
    private Object msgTemp;

    public MsgHandleThread(ChannelHandlerContext ctx, Object msg) {
        this.msgTemp = msg;
        this.temp = ctx;
    }

    @Override
    public void run() {
        ByteBuf buf = (ByteBuf) msgTemp;
        byte[] buffer = new byte[buf.readableBytes()];
        buf.readBytes(buffer, 0, buffer.length);
        String req = new String(buffer);
        log.info("客户端收到服务器数据:[{}]", req);
        try {
            String returnMsg = this.getData(req);
            log.info("返回信息:[{}]", returnMsg);
            this.temp.writeAndFlush(returnMsg);
        } catch (Exception e) {
            log.error("【错误】" + e.getMessage());
            this.temp.writeAndFlush("【错误】" + e.getMessage());
        }
    }

    private String getData(String msg) {
        try {
            String reqXml = msg.substring(msg.indexOf("<Root>"));
            Document doc = XmlUtil.parseText(reqXml);
            String head = MsgFieldConstant.SPLIT_STR + MsgFieldConstant.ROOT + MsgFieldConstant.SPLIT_STR + MsgFieldConstant.HEAD;
            String entNum = XmlUtil.getNodeText(doc, head, MsgFieldConstant.ENTERPRISE_NUM);
            String commandCode = XmlUtil.getNodeText(doc, head, MsgFieldConstant.COMMAND_CODE);
            String transSeqId = XmlUtil.getNodeText(doc, head, MsgFieldConstant.TRANS_SEQ_ID);
            String req = MsgFieldConstant.SPLIT_STR + MsgFieldConstant.ROOT + MsgFieldConstant.SPLIT_STR + "ReconciliationNoticeReq";
            String reconcileDate = XmlUtil.getNodeText(doc, req, MsgFieldConstant.RECONCILE_DATE);

            ReturnConfigDTO returnConfigDTO = ReturnConfiguration.returnConfigDTO;
            int returnTime = returnConfigDTO.getReturnTime();
            //休眠
            Thread.sleep(returnTime*1000);

            String returnKey = returnConfigDTO.getReturnKey();
            String[] keyArr = returnKey.split(StrUtil.COMMA);
            List<String> keyList = Arrays.asList(keyArr);
            List<ReturnInfoDTO> returnInfoDTOList = returnConfigDTO.getReturnInfoList();
            returnInfoDTOList.removeIf(returnInfoDTO -> !keyList.contains(returnInfoDTO.getKey()));
            if (returnInfoDTOList.size()==0){
                return "返回信息配置不正确";
            }
            int index = (int)(Math.random()*(returnInfoDTOList.size()));
            ReturnInfoDTO returnInfoDTO = returnInfoDTOList.get(index);
            ReconciliationNoticeResp resp = ReconciliationNoticeResp.builder()
                    .resultInfo(returnInfoDTO.getResultInfo())
                    .resultState(returnInfoDTO.getResultState())
                    .reconcileDate(reconcileDate)
                    .entNum(entNum)
                    .commandCode(commandCode)
                    .transSeqId(transSeqId)
                    .build();
            String xml = TemplateHolder.getValue(resp);
            return StringUtil.lengthFillBlank(xml.getBytes("gbk").length, 8) + xml;
        } catch (Exception ex) {
            log.error("发生异常", ex);
            return ex.getMessage();
        }
    }
}
